<template>
  <el-card class="list-page">
    <div class="list-h">
      <div>
        <el-button
          type="primary"
          @click="handleDetail(1, {})"
          v-auth="`/projects/purchase--add`"
          class="add-option"
          >新增</el-button
        >
        <el-button
          type="primary"
          @click="showImport = true"
          v-auth="`/projects/purchase--import`"
          class="add-option"
          >导入</el-button
        >
        <el-button
          type="primary"
          @click="exportFunc"
          v-auth="`/projects/purchase--export`"
          class="add-option"
          >导出</el-button
        >
      </div>
      <el-form
        :inline="true"
        :model="formInline"
        ref="formRef"
        class="demo-form-inline"
      >
        <el-form-item label="集采项目编号" prop="jcProjectCodeLike">
          <el-input
            class="width-custom120"
            v-model="formInline.jcProjectCodeLike"
          />
        </el-form-item>

        <el-form-item label="集采项目名称" prop="jcProjectNameLike">
          <el-input
            class="width-custom120"
            v-model="formInline.jcProjectNameLike"
          />
        </el-form-item>

        <el-form-item label="当前状态" prop="currentStateCode">
          <el-select
            class="width-custom140"
            v-model="formInline.currentStateCode"
            clearable
            filterable
          >
            <el-option
              v-for="item in statusList"
              :label="item.dicValue"
              :key="item.dicCode"
              :value="item.dicCode"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="采购方式" prop="proMethodCode">
          <el-select
            clearable
            filterable
            class="width-custom140"
            v-model="formInline.proMethodCode"
          >
            <el-option
              v-for="item in methodList"
              :label="item.dicValue"
              :key="item.dicCode"
              :value="item.dicCode"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="专业方向" prop="professionDirCode">
          <el-select
            clearable
            filterable
            class="width-custom140"
            v-model="formInline.professionDirCode"
          >
            <el-option
              v-for="item in professionList"
              :label="item.dicValue"
              :key="item.dicCode"
              :value="item.dicCode"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="负责人" prop="jcLeaderNameLike">
          <el-input
            class="width-custom120"
            v-model="formInline.jcLeaderNameLike"
          />
        </el-form-item>

        <el-form-item label="创建时间">
          <el-date-picker
            class="width-custom230"
            v-model="timeValue"
            type="daterange"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="handleChangeDate"
          />
        </el-form-item>
        <el-form-item class="btn-wrap">
          <el-button @click="handleReset">重置</el-button>
          <el-button
            type="primary"
            @click="handleSearch"
            v-auth="`/projects/purchase--query`"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <el-skeleton
      style="height: calc(100vh - 340px)"
      :rows="8"
      :loading="loading"
      animated
    >
    </el-skeleton>
    <el-table
      :data="tableData"
      stripe
      style="width: 100%"
      v-loading="loading"
      v-show="!loading"
      :height="'calc(100vh - 340px)'"
      :header-cell-style="{
        background: '#F7F9FD',
        color: '#000',
        height: '48px',
        borderTop: '1px soild #E4E8F2'
      }"
    >
      <template #empty>
        <el-empty :image-size="150" description="暂无数据"></el-empty>
      </template>

      <el-table-column type="index" label="序号" width="80">
        <template v-slot="scope">
          <span>{{
            (pageState.pageNum - 1) * pageState.pageSize + scope.$index + 1
          }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="jcProjectCode" label="集采项目编号">
      </el-table-column>
      <el-table-column prop="jcProjectName" label="集采项目名称">
      </el-table-column>
      <el-table-column
        prop="purchasSchemeName"
        label="关联招标方案"
      ></el-table-column>
      <el-table-column prop="currentStateName" label="当前状态">
      </el-table-column>
      <el-table-column prop="proMethodName" label="采购方式"> </el-table-column>
      <el-table-column
        prop="professionDirName"
        label="专业方向"
      ></el-table-column>
      <el-table-column prop="budgetAmount" label="预算金额（万）">
      </el-table-column>
      <el-table-column prop="remainAmount" label="剩余金额（万）">
        <template #default="{ row }">
          <span :class="Number(row.remainAmount) < 0 ? 'text-danger' : ''">{{
            row.remainAmount
          }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="jcLeaderName" label="负责人"></el-table-column>
      <el-table-column prop="createTime" label="创建时间"> </el-table-column>
      <el-table-column fixed="right" label="操作" width="180">
        <template #default="{ row, $index }">
          <el-button
            type="text"
            size="small"
            @click="handleRelation(row, $index)"
            v-auth="`/projects/purchase--relation`"
            >关联项目</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="handleDetail(2, row)"
            v-auth="`/projects/purchase--edit`"
            >编辑</el-button
          >
          <el-button
            type="text"
            size="small"
            class="btns-danger"
            @click="showDeleteMessageBox(row)"
            v-auth="`/projectsS/purchase--delete`"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <re-pagination
      v-if="total > 0"
      :total="total"
      v-model:page="pageState.pageNum"
      v-model:limit="pageState.pageSize"
      @pagination="handleChangePage"
    />

    <el-dialog
      :title="detailData.title"
      v-model="detailData.dialogFormVisible"
      destroy-on-close
      width="520px"
    >
      <purchase-detail
        :purId="detailData.purId"
        :methodList="methodList"
        :professionList="professionList"
        @emitClose="detailData.dialogFormVisible = false"
        @updateClose="updateClose"
      />
    </el-dialog>

    <relation-project
      v-if="relationData.isShowRelation"
      :relationInfo="relationData.data"
      @updateClose="updateClose"
      @handleCancel="relationData.isShowRelation = false"
    ></relation-project>

    <import-dom
      v-if="showImport"
      ref="importRef"
      @cancel="showImport = false"
      @submit="submitImport"
    ></import-dom>
  </el-card>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import RePagination from "/@/components/RePagination/index.vue";
import { cenPurList, delCenPurchas } from "/@/api/purchase";
import { postDictList } from "/@/api/home";
import purchaseDetail from "./components/purchaseDetail.vue";
import relationProject from "./components/relationProject.vue";
import importDom from "./components/import.vue";
import { ElMessageBox } from "element-plus";
import NotifMessage from "/@/utils/message/notification";
import { exportExcel } from "/@/utils/file";
import { importCenPurchas } from "/@/api/projects";
const formRef = ref<HTMLFormElement | null>(null) as any;
const importRef = ref<HTMLFormElement | null>(null) as any;
const initData = {
  jcProjectCodeLike: "",
  jcProjectNameLike: "",
  jcLeaderNameLike: "",
  currentStateCode: "",
  proMethodCode: "",
  professionDirCode: "",
  createTimeStrStart: "",
  createTimeStrEnd: ""
};
const formInline = reactive(initData);
const timeValue = ref(null);
const methodList = ref([]);
const professionList = ref([]);
const statusList = ref([]);
const showImport = ref(false);
const itemList = [
  { key: methodList, value: "thd_cen_pro_method" },
  { key: professionList, value: "thd_cen_profession_dir" },
  { key: statusList, value: "thd_cen_current_state" }
];

const pageState = reactive({
  pageNum: 1,
  pageSize: 10
});
const tableData = ref([]);
const total = ref<number>(0);
const loading = ref<boolean>(false);
const formParams = ref<typeof initData>({ ...initData });
const detailData = reactive({
  type: 1,
  purId: "",
  dialogFormVisible: false,
  title: "新增集采项目"
});
const relationData = reactive({
  isShowRelation: false,
  index: 0,
  data: {}
});

//获取数据列表
const getTableList = async (obj: object = {}) => {
  try {
    loading.value = true;
    const { code, data } = await cenPurList({
      ...obj,
      ...pageState
    });
    if (code === 200) {
      tableData.value = data.list;
      total.value = data.rows;
      if (relationData.isShowRelation) {
        if (tableData.value?.length) {
          //编辑新增关联项目时，实时更新该项目的剩余预算
          relationData.data = tableData.value[relationData.index];
        }
      }
    }
  } catch (err) {
    console.log(err);
  } finally {
    loading.value = false;
  }
};

//新增编辑集采项目
const handleDetail = async (type, row) => {
  if (type === 1) {
    detailData.title = "新增集采项目";
    detailData.type = 1;
    detailData.purId = "";
  } else {
    detailData.title = "编辑集采项目";
    detailData.type = 2;
    detailData.purId = row.id;
  }
  detailData.dialogFormVisible = true;
};

const updateClose = async () => {
  getTableList(formInline);
  detailData.dialogFormVisible = false;
};

const showDeleteMessageBox = row => {
  ElMessageBox.confirm("确定删除该条记录吗？", "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    iconClass: "el-icon-warning"
  })
    .then(() => {
      handleDelete(row);
    })
    .catch(() => {});
};

const handleDelete = async row => {
  try {
    const { code, message } = await delCenPurchas({ id: row.id });
    if (code === 200) {
      NotifMessage.success(message);
      getTableList(formInline);
    } else {
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
};

//集采项目关联项目
const handleRelation = async (row, $index) => {
  relationData.index = $index;
  relationData.data = row;
  relationData.isShowRelation = true;
};

// 数据字典
const initPostDictList = async item => {
  try {
    const { data } = await postDictList({ dicType: item.value });
    item["key"].value = data;
  } catch (err) {
    console.log(err);
  }
};

//改变时间
const handleChangeDate = item => {
  if (item) {
    formInline.createTimeStrStart = item[0];
    formInline.createTimeStrEnd = item[1];
  } else {
    formInline.createTimeStrStart = "";
    formInline.createTimeStrEnd = "";
  }
};

const handleReset = () => {
  formRef.value.resetFields();
  timeValue.value = null;
  formParams.value = initData;
  handleChangeDate(null);
  getTableList(formInline);
};

const handleSearch = () => {
  pageState.pageNum = 1;
  formParams.value = formInline;
  getTableList(formInline);
};

const handleChangePage = () => {
  getTableList(formParams.value);
};

const submitImport = async formData => {
  try {
    const { code, message } = await importCenPurchas(formData);
    if (code === 200) {
      NotifMessage.success(message);
      showImport.value = false;
      handleSearch();
    } else {
      NotifMessage.error(message || "请重试");
    }
  } catch (err) {
    importRef.value.handleRemove();
  }
};

const exportFunc = async () => {
  let formData = {
    ...formInline,
    pageNum: 1,
    pageSize: 0
  };
  exportExcel("/snow-admin/cenPurchas/export", formData, `集采项目`);
};

onMounted(() => {
  itemList.forEach(item => {
    initPostDictList(item);
  });
});
getTableList(formInline);
</script>

<style>
.el-icon-question {
  color: #ffc069;
}
.el-icon-warning {
  color: #e45d5d !important;
}
</style>

<style scoped lang="scss">
.text-danger {
  color: #e45d5d;
}
</style>
